/**
 * Created by tuniao on 2020/1/2
 */
import {
  checkUserExist,
  updateUserInfo
} from '@/api/user'

/**
 * 检查用户是否已经授权登陆
 */
export function checkUserScope() {
  const app = getApp();
  return new Promise((reslove, reject) => {
    //判断用户是否已经更新过信息
    if (app.globalData.isUpdateUserInfo == true) {
      reslove(true);
    } else {
      uni.login({
        provider:"weixin",
        success: (res) => {
          checkUserExist(res.code).then((existRes) => {
            if (existRes) {
              app.globalData.isUpdateUserInfo = true
              reslove(true)
            } else {
              reject(false)
            }
          }).catch(() => {
            reject(false)
          })
        }
      })
    }
  })
}

/**
 * 更新用户信息到服务器上
 * params:
 * userInfo 需要上传到服务器的用户信息
 */
export function updateUserInfoToServer(res) {
  // console.log(userInfo);
  const app = getApp();
  return new Promise((resolve, reject) => {
    if (!app.globalData.isUpdateUserInfo) {
      updateUserInfo({
        nick_name: res.userInfo.nickName,
        avatar_url: res.userInfo.avatarUrl,
        gender: res.userInfo.gender,
        rawData: res.rawData,
        signature: res.signature,
        encryptedData: res.encryptedData,
        iv: res.iv
      }).then((res) => {
        console.log(res);
        if (res.errorCode === 0) {
          app.globalData.isUpdateUserInfo = true;
          resolve()
        } else {
          reject()
        }
      }).catch(() => {
        reject()
      })
    }
    resolve()
  })

}
